package main

import (
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/sirupsen/logrus"
	"net/http"
	"strings"
)

var ruleMetric = prometheus.NewGaugeVec(
	prometheus.GaugeOpts{
		Name: "rule_metric",
		Help: "Metric for rules monitoring",
	},
	[]string{"rule_name"},
)

// Metric 自定义Prometheus Metrics
func Metric(alert string, triggerTimes float64) {
	ruleMetric.WithLabelValues(alert).Set(triggerTimes)
}

// Primary 根路径
func Primary(c *gin.Context) {
	// 解析请求参数
	err := c.Request.ParseForm()
	if err != nil {
		logrus.Errorf("解析请求参数失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "解析参数失败"})
		return
	}

	// 输出请求的路径
	logrus.Infof("接收到请求，路径: %s", c.Request.URL.Path)

	// 输出查询参数
	if len(c.Request.Form) > 0 {
		logrus.Infof("请求参数:")
		for k, v := range c.Request.Form {
			logrus.Infof("key: %s, value: %s", k, strings.Join(v, ","))
		}
	} else {
		logrus.Info("请求没有参数")
	}

	// 向客户端输出项目文档链接
	c.String(http.StatusOK, "项目文档：https://gitee.com/yunwe/esalert.git")
}

func LoadRulesAPIHandler(c *gin.Context) {
	// 检查是否为 POST 请求
	if c.Request.Method != http.MethodPost {
		c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "Invalid request method"})
		return
	}

	// 从请求体中读取规则
	var newRules []Rule
	if err := c.ShouldBindJSON(&newRules); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to parse JSON"})
		return
	}
	CheckYaml()
	// 更新规则缓存
	cacheMutex.Lock()
	defer cacheMutex.Unlock()

	// 返回响应
	c.JSON(http.StatusOK, gin.H{"message": "Rules updated successfully"})
}
